<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(0);
header('Content-Type: text/html; charset=utf-8');

class Auth extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->library('session');
        $this->load->model('users_model');
        $this->load->model('crud_model');
        $this->load->library('../controllers/crud');
        $this->load->library("pagination");
        $this->load->library('email');
    }
    public function session($provider)
    {
        header('Content-Type: text/html; charset=UTF-8');

        $this->load->spark('oauth2/0.4.0');

        if($provider == "google"){
            $provider = $this->oauth2->provider($provider, array(
                'id' => '722510708736-eg6jmupqeemueb16t2p5nn4itp9fbe73.apps.googleusercontent.com',
                'secret' => 'fxG2sT2-WqJtTih89qN9Wagk',
            ));
        }

        if($provider == "facebook"){
            $provider = $this->oauth2->provider($provider, array(
                'id' => '893884397289221',
                'secret' => '30aee252ed8c3df1aed933f554874a02',
            ));
        }

        if ( ! $this->input->get('code'))
        {
            // By sending no options it'll come back here
            $url = $provider->authorize();

            redirect($url);
        }
        else
        {
            try
            {
                error_reporting(0);
                // Have a go at creating an access token from the code
                $token = $provider->access($_GET['code']);

                // Use this object to try and get some user details (username, full name, etc)
                $user = $provider->get_user_info($token);

                // Here you should use this information to A) look for a user B) help a new user sign up with existing data.
                // If you store it all in a cookie and redirect to a registration page this is crazy-simple.
//                echo "<pre>Tokens: ";
//                var_dump($token);
//
//                echo "\n\nUser Info: ";
//                print_r($user);
                $username = $user[name];
                $email = $user[email];
                $this->checkRegister($username, $email);
            }

            catch (OAuth2_Exception $e)
            {
                show_error('That didnt work: '.$e);
            }

        }
    }

    public function checkRegister($username, $email){
        if (!empty($email) && !empty($username)) {
            $password = mt_rand(100000, 999999); //random 1 chuoi gom 6 ky tu
            $passwordEncrypt = md5($password);

            $dt = date("Y-m-d H:i:s");
            $expired_active = date( "Y-m-d H:i:s", strtotime( "$dt +2 day" ) ); //cong them 2 ngay

            $checkEmail = $this->users_model->getEmail($email);
            if($checkEmail != 0){
                $this->registerEmailFail($email);
            }
            else{
                $confirm_code=md5(uniqid(rand()));
                $table = "users";
                $data = array(
                    'email' => $email,
                    'password' => $passwordEncrypt,
                    'name' => $username,
                    'confirm_code' => $confirm_code,
                    'active' => '0',
                    'expired_active' => $expired_active,
                    'admin' => '0'

                );
                $query = $this->crud_model->insert($table, $data);
                if($query != 0){
                    echo $query;
                }
                else{
                    $date = date("d-m-Y");
                    $info = array(
                        'email' => $email,
                        'name' => $username,
                        'password' => $password,
                        'key' => $confirm_code,
                        'date' => $date
                    );

                    $result = $this->crud->subscribe($email, "Xác nhận đăng ký tài khoản bằng mạng xã hội", "mail/register", $info);
                    if($result == 0){
                        $this->registerSuccess();
                    }
                    else{
                        echo $result;
                    }
                }
            }
        }
        else{
            header('Location: '.base_url().'register/fail');
        }
    }

    public function registerEmailFail($email){
        $data['email'] = $email;
        $this->load->view('head');
        $this->load->view('register/email_fail', $data);
    }

    public function registerFail(){
        $this->load->view('head');
        $this->load->view('register/fail');
    }

    public function registerSuccess(){
        $this->load->view('head');
        $this->load->view('register/success');
    }
}